<%@ page contentType="text/html;charset=UTF-8" language="java"%>

<!DOCTYPE html>
<html lang="en">
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>tree-table</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/plugin/css/layui.css">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/plugin/css/common.css"/>
		
	<link href="${pageContext.request.contextPath}/plugin/css/bootstrap.min.css" rel="stylesheet">
	<!-- jquery -->
	<script src="${pageContext.request.contextPath}/plugin/js/jquery-3.2.1.min.js"></script>
	<script src="${pageContext.request.contextPath}/plugin/js/bootstrap.min.js"></script>
	
	 <style>
        input {
            height: 33px;
            line-height: 33px;
            padding: 0 7px;
            border: 1px solid #ccc;
            border-radius: 2px;
            margin-bottom: -2px;
            outline: none;
        }

        input:focus {
            border-color: #009E94;
        }
    </style>

</head>
<body>
<div >

   
    <div class="layui-btn-group" style="float:left">
	   
        <button class="layui-btn" id="btn-expand">全部展开</button>
        <button class="layui-btn" id="btn-fold">全部折叠</button>
        <button class="layui-btn" id="btn-refresh">刷新表格</button>

    </div>
    
    
      &nbsp;&nbsp;
    <button class="layui-btn" id="btn-search"  style="float:right" >&nbsp;&nbsp;搜索&nbsp;&nbsp;</button>
    <input id="edt-search" type="text" placeholder="输入关键字" style="width: 120px; float:right"/>&nbsp;&nbsp;
    
    <table id="auth-table" class="layui-table" lay-filter="auth-table" ></table>
</div>


<!-- 更新界面开始 -->
<div class="modal fade" id="updatemyModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                <h4 class="modal-title" id="updatemyModalLabel">更新部门</h4>
            </div>
            <div class="modal-body">
                <form id="updateff_p">
               
                       
                
                	<div class="form-group">
                        <label >部门编号</label>;
                        <input type="text" name="departmentId" class="form-control" id="departmentId"  readonly="readonly">
                    </div>
                
                
                   <div class="form-group">
                        <label for="updatedptname">部门名称</label> &nbsp;&nbsp;&nbsp;<label class = "dpetnameNULL" hidden="yes" style="color: red;">部门不能为空!</label>
                        <input type="text" name="departmentName" class="form-control" id="updatedptname" placeholder="部门名称" required="required">
                    </div>

                    <div class="form-group">
                        <label>部门主管</label>
                        <select id="select_dpt_id_update" name="departmentHeaderId"  class="form-control"></select>
                          
                    </div>                    
         
                 	 <div class="form-group">                   
                        <label for="adddptdescription">上级部门</label>
                        <select id="select_dpt_parent_update" name="departmentParentId"  class="form-control"></select>    
                    </div>
                           
                      <div class="form-group">
                        <label for="adddptemail">部门邮箱</label> &nbsp;&nbsp;&nbsp;<label class = "dpetemailNULL" hidden="yes" style="color: red;"></label>
                        <input type="text" name="departmentEmail" class="form-control" id="updatedptemail" placeholder="部门邮箱" >
                    </div>     
                              
                	 <div class="form-group">
                        <label for="adddptdescription">部门描述</label>
                  		<textarea rows="4" cols="20" class="form-control" name="departmentDescription" id="updatedptdescription" placeholder="部门描述"></textarea>
                    </div>                               
                    
                    
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>关闭</button>
                        <button type="button" id="btn_update" class="btn btn-primary" data-dismiss="modal" onclick="myb()"><span class="glyphicon glyphicon-floppy-disk" aria-hidden="true" ></span>保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 更新界面结束 -->


<!-- 新增页面开始  -->
<div class="modal fade" id="add_dpt" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                <h4 class="modal-title" id="add_dpt_header">新增</h4>
            </div>
            <div class="modal-body">
                <form id="add_form" >    
                
                    <div class="form-group">
                        <label for="adddptname">部门名称</label> &nbsp;&nbsp;&nbsp;<label class = "dpetnameNULL" hidden="yes" style="color: red;"></label>
                        <input type="text" name="departmentName" class="form-control" id="adddptname" placeholder="部门名称" required="required">
                    </div>

                    <div class="form-group">
                        <label>部门主管</label>
                        <select id="select_dpt_id" name="departmentHeaderId"  class="form-control"></select>
                          
                    </div>                    
         
                
                      <div class="form-group">
                        <label for="adddptemail">部门邮箱</label> &nbsp;&nbsp;&nbsp;<label class = "dpetemailNULL" hidden="yes" style="color: red;"></label>
                        <input type="text" name="departmentEmail" class="form-control" id="adddptemail" placeholder="部门邮箱" >
                    </div>     
                              
                	 <div class="form-group">
                        <label for="adddptdescription">部门描述</label>
                  		<textarea rows="4" cols="20" class="form-control" name="departmentDescription" id="adddptdescription" placeholder="部门描述"></textarea>
                    </div>                               
                 
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>关闭</button>
                        <button type="button" id="btn_submit" class="btn btn-primary" data-dismiss="modal" onclick="mya()"><span class="glyphicon glyphicon-floppy-disk" aria-hidden="true" ></span>保存</button>
                    </div>
                </form >
            </div >
        </div>
    </div>
</div>
<!-- 新增界面结束 -->

<!-- 操作列 -->
<script type="text/html" id="auth-state">
	<a class="layui-btn layui-btn-success layui-btn-xs" lay-event="add">添加</a>
    <a class="layui-btn layui-bg-orange layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script src="${pageContext.request.contextPath}/plugin/js/layui.js"></script>

<script>
var departmentParentId  = 0;


$(document).ready(function(){
	  $("input[name='departmentName']").blur(function(){
		  var str =  $.trim($(this).val());
			if ("" == str) {
				 $(".dpetnameNULL").html("部门不能为空!");
				 $(".dpetnameNULL").show();
			}else {
				 $(".dpetnameNULL").hide();
		
				 $.ajax({
		         type:"get",
		         url: "${pageContext.request.contextPath}/dept/check/departmentName/"+str,
		         dataType : "json",
		         success:function(datas){
		       	 	if (512 == datas.state) {
		       	 		$(".dpetnameNULL").html("字段重复!");
		       	 	 	$(".dpetnameNULL").show();
					}   	 
		         }
		     });		 
		}
	  });
	});


$(document).ready(function(){

	  $("input[name='departmentEmail']").blur(function(){
		  var str =  $.trim($(this).val());
			if ("" == str) {
				 $(".dpetemailNULL").html("邮箱不能为空!");
				 $(".dpetemailNULL").show();
			}else {
				 $(".dpetemailNULL").hide();
					
				 $.ajax({
		         type:"get",
		         url: "${pageContext.request.contextPath}/dept/check/departmentEmail/"+str,
		         dataType : "json",
		         success:function(datas){
		       	 	if (512 == datas.state) {
		       	 		$(".dpetemailNULL").html("字段重复!");
		       	 	 	$(".dpetemailNULL").show();
					}   	 
		         }
		     });	
			}
	  });
	});


//修改
 function  edit(department) {
 	getdept();
 	getemp();
    $('#departmentId').val(department.departmentId);
    $('#updatedptname').val(department.departmentName);
    $('#updatedptemail').val(department.departmentEmail);
    $('#updatedptdescription').val(department.departmentDescription);             
    $('#updatemyModal').modal();
 };


 //删除
function del(id) {
         $.ajax({
             type:"DELETE",
             url:"${pageContext.request.contextPath }/dept/dept/"+id,
             contentType : "application/json; charset=utf-8",
             success:function(datas){       
                 if(203 == datas.state){   
                	 layer.msg("删除成功");
                	 $("#btn-refresh").click()
                   }else{
                	   layer.msg("删除失败", {icon: 5});
                 }
             }
         });
     }
     

 
 
function getdept() {
	 $.ajax({
        type:"get",
        url: "${pageContext.request.contextPath}/dept/dept",
        dataType : "json",
        success:function(datas){
      	  $("select[name='departmentParentId']").html('<option value="0">无</option>');
      	  $.each(datas.data, function(index, dept) {
      	     $("select[name='departmentParentId']").append('<option value="'+dept.departmentId+'">'+dept.departmentName+'</option>');          		  
      	  });
        }
    });
}


function getemp() {
	  $.ajax({
	         type:"GET",
	         url: "${pageContext.request.contextPath}/emp/emp",
	         dataType : "json",
	         success:function(datas){
	       	  $("select[name='departmentHeaderId']").html("");
	       	  $.each(datas.data.employees, function(index, emp) {
	       	     $("select[name='departmentHeaderId']").append('<option value="'+emp.empId+'">'+emp.empName+'</option>');          		  
	             });
	         }
	    });	
}


//提交添加：
function mya(){	

	var departmentName = $("#adddptname").val();
	var departmentHeaderId = $("#select_dpt_id").val();
	var departmentEmail = $("#adddptemail").val();
	var departmentDescription = $("#adddptdescription").val();

	var department = {"departmentName":departmentName,"departmentHeaderId":departmentHeaderId,"departmentEmail":departmentEmail,"departmentDescription":departmentDescription,"departmentParentId":departmentParentId};
	
	$.ajax({
        type:"post",
        url: "${pageContext.request.contextPath}/dept/dept",
        dataType : "json",
        contentType : "application/json; charset=utf-8",
        data: JSON.stringify(department),
        
        success:function(datas){
      	 	if (202 == datas.state) {   
      	 		layer.msg("添加成功");
      	 		$("#btn-refresh").click()
			}else {					
				layer.msg("添加失败", {icon: 5});
			}       	
        }
    });
 }



//修改提交：
function myb(){
		var departmentId = $("#departmentId").val();
		var departmentName = $("#updatedptname").val();
		var departmentHeaderId = $("#select_dpt_id_update").val();
		var departmentEmail = $("#updatedptemail").val();
		var departmentDescription = $("#updatedptdescription").val();
		var departmentParentId = $("#select_dpt_parent_update").val();
		
		var department = {"departmentId":departmentId,"departmentName":departmentName,"departmentHeaderId":departmentHeaderId,"departmentEmail":departmentEmail,"departmentDescription":departmentDescription,"departmentParentId":departmentParentId};
	 
  $.ajax({
      type:"put",
      url:"${pageContext.request.contextPath }/dept/dept",
      dataType : "json",
      data: JSON.stringify(department),
      contentType : "application/json; charset=utf-8",
      success:function(datas){
          if(205 == datas.state){  
        	  layer.msg("修改成功");
        	  $("#btn-refresh").click()
          }else{
        	  layer.msg("修改失败", {icon: 5});
          }
      }
  });
}   



</script>





<script>
    layui.config({
        base: '${pageContext.request.contextPath}/plugin/js/modules/module/'
    }).extend({
        treetable: 'treetable-lay/treetable'
    }).use(['table', 'treetable'], function () {
        var $ = layui.jquery;
        var table = layui.table;
        var treetable = layui.treetable;

	   	 function getdatas() {
		 	 	var treeData = [];
		 		  $.ajax({
		 			async: false, 
		 	     	type:"get",
		 	        url: "${pageContext.request.contextPath}/dept/dept",
		 	        dataType : "json",
		 	        contentType : "application/json; charset=utf-8",      
		 	        success:function(datas){	 
		 	        	$.each(datas.data, function(index, department) {
		 	        		department.departmentCreatedTime = department.departmentCreatedTime.substring(0,10);
		 	        		treeData.push(department);                   	
		 	         	});
		 	       	 	         }
		 		}); //ajax结束 
		 		return treeData;
		 	  };  	 	  
		 	
        // 渲染表格
       var renderTable = function() {
        layer.load(2);
        treetable.render({
            treeColIndex:1,
            treeSpid: 0,
            treeIdName: 'departmentId',
            treePidName: 'departmentParentId',
            elem: '#auth-table',
            data : getdatas(),
            treeDefaultClose: true,
            page: false,
            cols: [[
                {type: 'numbers'},
                {field: 'departmentName', minWidth: 200, title: '部门名称'},
                {field: 'departmentEmail', title: '部门邮箱'},
                {field: 'departmentCreatedTime', minWidth: 140, align: 'center', title: '创建时间'},
                {field: 'departmentDescription', title: '部门介绍'},
                {
                    field: 'departmentHeaderId', minWidth: 120, align: 'center', templet: function (d) {
                     	if (d.departmentParentId == 0) {
                            return '<span class="layui-badge layui-bg-blue">顶级部门</span>';
                        }else {
                            return '<span class="layui-badge-rim">子部门</span>';
                        }                  
                        
                    }, title: '类型'
                },
                {templet: '#auth-state', minWidth: 180, align: 'center', title: '操作'}
            ]],
            done: function () {
                layer.closeAll('loading');
            }
        });
        }
        renderTable();
        
        

        $('#btn-expand').click(function () {
            treetable.expandAll('#auth-table');
        });

        $('#btn-fold').click(function () {
            treetable.foldAll('#auth-table');
        });
        
        $('#btn-refresh').click(function () {
            renderTable();
        });
        
        table.on('tool(auth-table)', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;

            if (layEvent === 'del') {
            	del(data.departmentId);
            	
            } else if (layEvent === 'edit') {
            	edit(data);
            	
            }else if (layEvent === 'add') {
            	departmentParentId  = data.departmentId ; 
                getemp();
                $('#add_dpt').modal();
            }
            
        });
        
        
        $('#btn-search').click(function () {
            var keyword = $('#edt-search').val();
            var searchCount = 0;
            $('#auth-table').next('.treeTable').find('.layui-table-body tbody tr td').each(function () {
                $(this).css('background-color', 'transparent');
                var text = $(this).text();
                if (keyword != '' && text.indexOf(keyword) >= 0) {
                    $(this).css('background-color', 'rgba(250,230,160,0.5)');
                    if (searchCount == 0) {
                        treetable.expandAll('#auth-table');
                        $('html,body').stop(true);
                        $('html,body').animate({scrollTop: $(this).offset().top - 150}, 500);
                    }
                    searchCount++;
                }
            });
            if (keyword == '') {
                layer.msg("请输入搜索内容", {icon: 5});
            } else if (searchCount == 0) {
                layer.msg("没有匹配结果", {icon: 5});
            }
        });

        
    });
</script>
</body>
</html>